
import * as PIXI from 'pixi.js';
import Rect from 'components/rect';
import Image from 'components/image';
import Text from 'components/text';
import injectStore from 'components/injectStore';
import ajax from 'common/utils/ajax';
import RealGoods from './prompts/realGoods';
import ShopCoupon from './prompts/shopCoupon';
import TmallCoupon from './prompts/tmallCoupon';
const { Container } = PIXI;

@injectStore
export default class DrawLottery {
  constructor({parent, CONST, store}) {
    this.CONST = CONST;
    this.parent = parent;
    this.store = store;
    this.container = new Container();

    this.hasDraw = false;

    const {view} = window.CFG;
    const {height, width } = this.CONST;
    this.awardModalSize = {
      width,
      height,
      top: (view.height - height) / 2,
      left: (view.width - width) / 2,
    };

    this._renderBg();
    this._renderBtn();
  }

  _renderBtn = (select) => {
    const { awardModalSize } = this;
    const { awardBtn, width, height, margin } = this.CONST.items;

    const containerSize = {
      top: awardModalSize.top + (awardModalSize.height - height * 3 - margin * 2) / 2 + 30,
      left: awardModalSize.left + (awardModalSize.width - width * 3 - margin * 2) / 2,
    };

    if (this.items && Object.values(this.items).length) {
      Object.values(this.items).forEach(item => {
        this.container.removeChild(item);
      });
    }

    const complete8 = (arr) => {
      if (arr.length >= 8) {
        return JSON.parse(JSON.stringify(arr.slice(0, 8)));
      }
      let newArr = [...arr, ...arr];
      return complete8(newArr);
    };
    // 奖品如果不够8个，强行凑到8个
    const awardArr = complete8(this.store.lotteryList.list).map((item, index) => {
      item.key = index;
      return item;
    });

    this.items = {};

    awardArr.forEach((item, index) => {

      const sort = index < 4 ? index + 1 : index + 2;
      const position = {
        row: Math.ceil(sort / 3),
        col: sort % 3 ? sort % 3 : 3,
      };

      let btn = new Rect({
        fill: item.key === select ? 0xf6e18e : 0xffffff,
        width,
        height,
        top: containerSize.top + (position.row - 1) * (height + margin),
        left: containerSize.left + (position.col - 1) * (width + margin),
      });

      let goods = new Image({
        src: item.img,
        width,
        height,
        top: containerSize.top + (position.row - 1) * (height + margin),
        left: containerSize.left + (position.col - 1) * (width + margin),
        isAdapt: true
      });

      // todo

      this.container.addChild(btn);
      this.container.addChild(goods);
      this.items[item.id] = btn;
      this.items[`goods_${item.id}`] = btn;
    });

    let beginBtn = new Image({
      src: awardBtn,
      width,
      height,
      top: containerSize.top + height + margin,
      left: containerSize.left + width + margin,
    });

    if (!this.hasDraw) {
      beginBtn.interactive = true;
      beginBtn.on('tap', () => {
        this.drawing();
      });
    }

    this.container.addChild(beginBtn);
    this.items.awardBtn = beginBtn;

  };

  _renderBg = () => {

    const {view} = window.CFG;
    const {awardModalSize} = this;
    const { awardBg, awardMaskColor, awardMaskOpacity} = this.CONST;

    this.bgMask = new Rect({
      width: view.width,
      height: view.height,
      left: 0,
      top: 0,
      fill: awardMaskColor,
    });
    this.bgMask.alpha = awardMaskOpacity;


    this.container.addChild(this.bgMask);


    if (!this.hasDraw) {
      this.bg = new Image({
        src: awardBg,
        ...awardModalSize,
      });
      let bgText = new Text({
        value: '幸运抽奖',
        top: awardModalSize.top + 20,
        fontSize: 52,
        fontWeight: 600,
        fill: 0xffffff
      });
      bgText.x = (view.width - 208) / 2;
      this.container.addChild(this.bg);
      this.container.addChild(bgText);
    }

  };

  drawing = async () => {
    const sxPlantGameUserToken = localStorage.getItem('sxPlantGameUserToken');

    console.log(localStorage.getItem('sxPlantGameUserToken'));
    const lotteryRes = await ajax.req(
      'lottery.getLotteryResult',
      {
        token: sxPlantGameUserToken,
      });

    console.log('---------------------', lotteryRes);

    if (lotteryRes.rtoken) {

      localStorage.setItem('sxPlantGameUserToken', lotteryRes.rtoken);

      // 玩一次游戏只能抽一次奖
      this.hasDraw = true;
      const {list} = this.store.lotteryList;

      const complete8 = (arr) => {
        if (arr.length >= 8) return JSON.parse(JSON.stringify(arr.slice(0, 8)));

        let newArr = [...arr, ...arr];
        return complete8(newArr);
      };

      // 奖品如果不够8个，强行凑到8个
      const awardArr = complete8(list).map((item, index) => {
        item.key = index;
        return item;
      });

      const selectAwards = awardArr.filter(item => item.id === lotteryRes.award.id);

      const selectAward = selectAwards[parseInt(Math.random() * selectAwards.length)];

      const rotateArr = [ awardArr[0], awardArr[1], awardArr[2], awardArr[4], awardArr[7], awardArr[6], awardArr[5], awardArr[3] ];

      // 选中项
      const newIndex = rotateArr.indexOf(selectAward);

      const reduction = 10;

      for (let i = 0; i <= 8 * 3 + newIndex; i++ ) {
        const index = i % 8;
        setTimeout(() => {
          this._renderBtn(rotateArr[index].key);
          if (i === 8 * 3 + newIndex) {
            setTimeout(() => {
              this.winning(lotteryRes.award, selectAward);
            }, 1000);

          }
        }, reduction * (1 + i) * (1 + i));
      }

    } else {
      console.log('没有中奖！');
    }
  };

  winning = (lottery, award) => {

    let Prompt = null;

    switch (lottery.type) {
      case '公司直发': {
        Prompt = RealGoods;
        ReactDom.render(<RealGoods lottery={lottery} award={award} onClose={this.closePrompt} />, document.getElementById('promptBox'));

        break;
      }
      case '天猫代金券': {
        ReactDom.render(<TmallCoupon lottery={lottery} award={award} onClose={this.closePrompt} />, document.getElementById('promptBox'));

        Prompt = TmallCoupon;
        break;
      }
      case '门店代金券': {
        ReactDom.render(<ShopCoupon lottery={lottery} award={award} onClose={this.closePrompt} />, document.getElementById('promptBox'));

        Prompt = ShopCoupon;
        break;
      }
    }

    // react渲染 弹窗
    // if (Prompt) {
    //   ReactDom.render(<Prompt lottery={lottery} award={award} onClose={this.closePrompt} />, document.getElementById('promptBox'));
    // }
  };

  closePrompt = (hasCue = false) => {
    ReactDom.unmountComponentAtNode(document.getElementById('promptBox'));
    this.parent._renderShare(hasCue);
  }

};
